
import 'package:gold/app/user_provider.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_gold.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/goods_list_model.dart';
import 'package:gold/model/list_model.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

/// @description: 首页状态控制
/// @author tangzhentao
/// @created at 21:39 2024/11/25

class HomeViewmodel extends Viewmodel {
  /// 刷新控制器
  final RefreshController controller = RefreshController();

  final List<GoodsListModel> goodsList = [];

  /// 页码
  int _page = 1;

  /// 加载数据
  Future loadFirst() async {
    await XfgNav.read<UserProvider>().requestGoldRealTimeQuotes();
    final result = await Http().request<ListModel<GoodsListModel>>(ApiGold.productList,
      data: {'page': _page, 'filter': {'keywords': ''}, 'sort': {'sales': 0, 'price': 0}}
    );
    goodsList.addAll(result.data?.list?? []);
    setSuccessChange();
    controller.headerMode?.value = RefreshStatus.canRefresh;
    controller.footerMode?.value = _page < (result.data?.lastPage?? 0) ? LoadStatus.canLoading:LoadStatus.noMore;
  }

  /// 刷新数据
  Future refresh() async {
    await XfgNav.read<UserProvider>().requestGoldRealTimeQuotes();
    _page = 1;
    final result = await Http().request<ListModel<GoodsListModel>>(ApiGold.productList,
        data: {'page': _page, 'filter': {'keywords': ''}, 'sort': {'sales': 0, 'price': 0}}
    );
    if (result.success) {
      controller.refreshCompleted();
      controller.footerMode?.value = _page < (result.data?.lastPage?? 0) ? LoadStatus.canLoading:LoadStatus.noMore;
      final data = result.data?.list?? [];
      if (data.isNotEmpty) {
        goodsList.clear();
        goodsList.addAll(data);
        setSuccessChange();
      }
    } else {
      controller.refreshFailed();
    }
  }

  /// 加载更多数据
  Future loadMore() async {
    _page++;
    final result = await Http().request<ListModel<GoodsListModel>>(ApiGold.productList,
        data: {'page': _page, 'filter': {'keywords': ''}, 'sort': {'sales': 0, 'price': 0}}
    );
    if (result.success) {
      controller.loadComplete();
      controller.footerMode?.value = _page < (result.data?.lastPage?? 0) ? LoadStatus.canLoading:LoadStatus.noMore;
      final data = result.data?.list?? [];
      if (data.isNotEmpty) {
        goodsList.addAll(data);
        setSuccessChange();
      } else {
        controller.loadNoData();
      }
    } else {
      controller.loadFailed();
    }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}
